import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/event_bus_util/eventbus_util.dart';
import 'package:yt_devops/components/format_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/text_width.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/func_utils.dart';

import '../../../../components/yt_text_style.dart';

class SiteSettingParamSetController extends GetxController {
    final TextEditingController runTimeController = TextEditingController();
    final TextEditingController currencyUnitController = TextEditingController();
    DateTime initTime = DateTime.now();
    int selectedCurrencyIndex = 0;
    int selectedCurrencyTemp = 0; //选择临时的货币index,因为确定按钮里面没有索引
    List<String> currencyUnitStringList = [];
    List<dynamic> currencyUnitList = [];
    String siteId = '';
    SiteServices siteServices = Get.put(SiteServices());
    int unitCode = 1;
    bool isOpen = false;
    bool isShowIntroduce = false;
    double topMargin  = 100;
    double leftMargin = 100;
    bool isCanSetUnit = true;
    bool isCanChangePush = true;
    @override
    void onInit() {
    super.onInit();
    if (Get.arguments != null && Get.arguments['siteId'] != null) {
        siteId = Get.arguments['siteId'].toString();
        getParameterSetting();
        getAlarmPush();
    }
    currencyUnitController.text = '';
    runTimeController.text = initTime.toString().substring(0,10);
    leftMargin = TextWidth.calculateTextSize(ResKey.alarmPush.tr, ytTextStyle(
        fontSize: 16, fontWeight: FontWeight.normal)) + 16.w + 2;
    isCanSetUnit = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingParameterSettingMonetaryUnitSetting]);//是否可以设置货币单位
    isCanChangePush = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingParameterSettingAlarmPushSetting]);//是否可以设置告警推送
    }

    @override
    void onReady() {

    }
    /// 获取参数设置
    getParameterSetting() async {
        showLoading();
       var result = await siteServices.getParameterSetting({'siteId':siteId},onError: (error){
           dismissLoading();
           handleException(error);
           return false;
       });
        dismissLoading();

       if(result != null){
           if(result['operationTime'] != null){
               initTime = FormatUtil.timeStrToTime(result['operationTime'].toString());
               runTimeController.text = result['operationTime'].toString();
           }
           if(result['monetaryUnit'] != null){
               unitCode = result['monetaryUnit'];
               getMonetaryUnit();
           }

       }
        update();
    }
    ///获取告警推送
    getAlarmPush() async {
        showLoading();
        var result = await siteServices.getSiteAlarmPush({'siteId':siteId},onError: (error){
            dismissLoading();
            handleException(error);
            return false;
        });
        dismissLoading();
        if(result != null){
           if(result['alarmPush'] != null && result['alarmPush'].toString() == '1'){
               isOpen = true;
           }else{
                isOpen = false;
           }
        }
        update();
    }
    setAlarmPush(bool alarmOpen) async {
        showLoading();
        var result = await siteServices.setSiteAlarmPush({
            'siteId':siteId,
            'alarmPush':alarmOpen ? '1' : '0'
        },onError: (error){
            dismissLoading();
            handleException(error);
            return false;
        });
        dismissLoading();
        if(result != null){
            isOpen = alarmOpen;
        }
        update();
    }
    /// 获取货币列表
    getMonetaryUnit() async {
        showLoading();
        var result = await siteServices.getMonetaryUnit(onError: (error){
            dismissLoading();
            handleException(error);
            return false;
        });
        dismissLoading();
        if(result != null && result is List){
            currencyUnitList = result;
            currencyUnitStringList.clear();
            for(int i = 0;i < currencyUnitList.length;i++){
                var element = currencyUnitList[i];
                currencyUnitStringList.add(element['unit'].toString());
                if(element['code'] == unitCode){
                    currencyUnitController.text = element['unit'].toString();
                    selectedCurrencyIndex = i;
                }
            }
        }
        update();
    }

    @override
    void onClose() {}

    chooseTime(){
        BrnPickerTitleConfig pickerTitleConfig =
         BrnPickerTitleConfig(titleContent: ResKey.pleSelect.tr);
        return BrnDatePicker.showDatePicker(
            Get.context!,
            pickerMode: BrnDateTimePickerMode.date,
            minuteDivider: 10,
            initialDateTime: initTime,
            maxDateTime:DateTime.now(),
            pickerTitleConfig: pickerTitleConfig,
            dateFormat: 'yyyy-MM-dd',
            onConfirm: (dateTime,selectedIndex){
                initTime = dateTime;
                runTimeController.text = initTime.toString().substring(0,10);
                update();
            },
        );
    }

    ///选择货币单位
    chooseCurrency(BuildContext context) {
        showDialog(
            context: context,
            builder: (_) => StatefulBuilder(
                builder: (context, state) {

                    return BrnSingleSelectDialogWidget(
                        isClose: true,
                        title: ResKey.pleaseSelectCurrencyUnit.tr,
                        conditions: currencyUnitStringList,
                        checkedItem: selectedCurrencyIndex == -1
                            ? null
                            : currencyUnitStringList[selectedCurrencyIndex],
                        submitText: ResKey.sure.tr,
                        isCustomFollowScroll: true,
                        themeData: BrnDialogConfig(
                            dialogWidth: 300.w,
                            contentTextStyle: BrnTextStyle(fontSize: 16.sp)),
                        onItemClick: (BuildContext context, int index) {
                            selectedCurrencyTemp = index;
                            update();
                        },
                        onSubmitClick: (data) {
                            selectedCurrencyIndex = selectedCurrencyTemp;
                            currencyUnitController.text =
                            currencyUnitStringList[selectedCurrencyIndex];
                            unitCode =
                            currencyUnitList[selectedCurrencyIndex]['code'];
                            setParam();

                        });
                },
            ));
    }

    setParam() async {
        var params = {
            "siteId": siteId,
            "operationTime": runTimeController.text,
            "monetaryUnit": unitCode
        };
        Log.d('params==' + params.toString());
        var result = await  siteServices.setParameterSetting(params,onError: (error){
            dismissLoading();
            handleException(error);
            return false;
        });
        if(result != null){
            showSuccessToast(ResKey.mineUserManagerSaveSuccess.tr);
            GetStorage storage = GetStorage();
            if(currencyUnitController.text =='USD'){
                storage.write('monetaryUnitName', '\$');
            }else if(currencyUnitController.text =='EUR'){
                storage.write('monetaryUnitName', '€');
            }else{
                storage.write('monetaryUnitName', ResKey.yuan.tr);
            }
            EventBusUtil.getInstance().fire(ChangeMonetaryUnit());
            Future.delayed(const Duration(milliseconds: 2000), () {
                Get.back();
            });
        }
        update();
    }
}
